#include <stdio.h>

#include "SDL/SDL_log.h"
#include "SDL/SDL.h"

#define WINDOW_HEIGHT 800
#define WINDOW_WIDHT 600

SDL_Window *window;
SDL_Renderer *render;

void draw(){
    //SDL_CreateRenderer 创建了了渲染器以后，下面的SDL_Surface代码就会失效了
    // SDL_Surface *screen = SDL_GetWindowSurface(window);
    // SDL_Rect white_bg = {0, 0, WINDOW_WIDHT/2, WINDOW_HEIGHT/2};
    // SDL_FillRect(screen, &white_bg, 0xffffffff);

    //使用render绘制白色背景
    SDL_SetRenderDrawColor(render, 255, 255, 255, 255);
    SDL_RenderClear(render);

    //开始绘制
    SDL_Rect white_bg = {0, 0, WINDOW_WIDHT/2, WINDOW_HEIGHT/2};
    SDL_SetRenderDrawColor(render, 255,0,0,255);
    SDL_RenderFillRect(render, &white_bg);
    //结束绘制

    SDL_RenderPresent(render);
    SDL_UpdateWindowSurface(window);
}

void event_loop(){
 //必须有事件处理，否则窗体出不来，
    while (1)
    {
       draw();
       SDL_Event event;
       while(SDL_PollEvent(&event)){
            printf("event is %#x\n", event.type); // test code
            if (SDL_QUIT == event.type) {
                return;
            }
       }
    }
}

int showWindow(){
    if(SDL_Init(SDL_INIT_VIDEO)){
       SDL_Log("init error : %s", SDL_GetError());
       return 1;
    }
    window = SDL_CreateWindow("title", 
                            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                            WINDOW_WIDHT, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
    if(window == NULL){
       SDL_Log("create window error %s", SDL_GetError());
       return 2;
    }

    //创建图形渲染器
    render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if(render == NULL){
       SDL_Log("create render error %s", SDL_GetError());
    }
    //事件循环
    event_loop();
    
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
}

int main()
{
    showWindow();
    return 0;
}